package webapi

import (
	"MqttCloudProtocolServer/publiclib/dbcontrol"
	"fmt"
	"net/http"

	"github.com/wonderivan/logger"
)

//DbCleanService 网关服务器注册API类。注册控制台
type DbCleanService struct {
	base ServiceBase
}

//Regist 注册
func (_this *DbCleanService) Regist(mux *http.ServeMux) {
	_this.base.Regist(mux)
	_this.base.path += "dbms"
	_this.base.HandleRegist("clean", _this.clean)
}

//Regist 注册
func (_this *DbCleanService) clean(w http.ResponseWriter, r *http.Request) {
	vars := r.URL.Query()
	if len(vars) > 0 {
		password := GetParam(vars, "password")
		if password == "5a743dbcc89ee45ebe8d90b532f01502" {
			con := new(dbcontrol.DBCon)
			if e, err := con.GetConnection(); err != nil {
				logger.Alert(err)
				fmt.Fprintln(w, "Failed")
				return
			} else if e != nil {
				_, err2 := con.ExecuteSQL("delete from userConf where deleted_at IS NOT NULL")
				if err2 != nil {
					logger.Alert(err)
					fmt.Fprintln(w, "Failed")
					return
				}
				_, err2 = con.ExecuteSQL("delete from userServer where deleted_at IS NOT NULL")
				if err2 != nil {
					logger.Alert(err)
					fmt.Fprintln(w, "Failed")
					return
				}
				_, err2 = con.ExecuteSQL("delete from tcpConf where deleted_at IS NOT NULL")
				if err2 != nil {
					logger.Alert(err)
					fmt.Fprintln(w, "Failed")
					return
				}
				_, err2 = con.ExecuteSQL("delete from mqttServer where deleted_at IS NOT NULL")
				if err2 != nil {
					logger.Alert(err)
					fmt.Fprintln(w, "Failed")
					return
				}
				_, err2 = con.ExecuteSQL("delete from mqttConf where deleted_at IS NOT NULL")
				if err2 != nil {
					logger.Alert(err)
					fmt.Fprintln(w, "Failed")
					return
				}
				fmt.Fprintln(w, "Success")
				return
			}
		}
	}
	fmt.Fprintln(w, "Failed")
	//return
}
